package main

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"math/rand"
	"net/http"
	"time"
)

const baseUrl1 string = "https://studygolang.com/topics?p=2"
const baseurl2 string = " http://127.0.0.1:5000/news/get_news"

func main() {
	total := 10
	for i := 0; i < total; i++ {
		time.Sleep(1)
		main_test()
	}
}

func main_test() {
	page := make(chan int)
	start := 0
	end := 10
	for i := start; i < end; i++ {
		go getResponse2(i, page)
	}
	// 循环读取 channel， 协调主、子go程调用顺序
	for i := start; i < end; i++ {
		fmt.Printf("这是第%d次请求完成\n", <-page)
	}
}

func getResponse1() {
	client := &http.Client{}
	request, err := http.NewRequest("GET", baseUrl1, nil)
	fmt.Println("request失败原因为：", err)
	request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0")
	response, err := client.Do(request)
	fmt.Println(response, err)
	dom, err1 := goquery.NewDocumentFromResponse(response)
	fmt.Println(dom, err1)
	dom.Find(".topics .topic").Each(func(i int, content *goquery.Selection) {
		title := content.Find(".title a").Text()
		fmt.Println(title)
	})

}

func getResponse2(i int, page chan<- int) {
	fmt.Printf("这是第%d次请求\n", i)
	client := &http.Client{}
	//url := baseurl2 + RandString(20)
	url := baseurl2
	request, _ := http.NewRequest("GET", url, nil)
	request.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0")
	_, err := client.Do(request)
	if err != nil {
		//fmt.Println("请求失败原因",err)
	}
	page <- i // 写入channel ，协调主go程与子go程调用顺序。
}

var r *rand.Rand

func init() {
	r = rand.New(rand.NewSource(time.Now().Unix()))
}

// RandString 生成随机字符串
func RandString(len int) string {
	bytes := make([]byte, len)
	for i := 0; i < len; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}
